package com.luoye.lj.platform.controller;

import com.luoye.lj.platform.model.UserModel;
import com.luoye.lj.platform.model.UserProfile;
import com.luoye.lj.platform.model.domain.AuthInfo;
import com.luoye.lj.platform.model.domain.RUnitInfo;
import com.luoye.lj.platform.model.domain.RoleInfo;
import com.luoye.lj.platform.model.domain.muser.MUserDetail;
import com.luoye.lj.platform.model.domain.muser.MUserInfo;
import com.luoye.lj.platform.model.domain.muser.MUserSaveInfo;
import com.luoye.lj.platform.model.enums.RoleType;
import com.luoye.lj.platform.model.enums.UnitType;
import com.luoye.lj.platform.model.enums.UserStatus;
import com.luoye.lj.platform.service.IMuserservice;
import com.luoye.lj.util.converter.DataConverter;
import com.luoye.lj.util.mvc.annotation.OperateLog;
import com.luoye.lj.util.mvc.data.SimpleResponseBody;
import com.luoye.lj.util.mvc.log.DefaultDescriptionGenerator;
import com.luoye.lj.util.strcheck.StrCheckUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Controller
@RequestMapping("/auth")
public class AuthenticationController {
    protected static final Logger logger = LoggerFactory.getLogger(AuthenticationController.class.getSimpleName());

	@Resource
    UserDetailsService customUserDetailsService;
	@Resource
    PasswordEncoder passwordEncoder;
    @Autowired
    private IMuserservice muserservice;
	
	@RequestMapping(value = "/login",method = RequestMethod.GET)
//    @OperateLog(value = "访问登录页面",description = "访问了登录界面")
	public String login(HttpServletRequest request,Model model){
		model.addAttribute("error", request.getParameter("error"));
        HttpSession session = request.getSession();
        session.invalidate();

        String pwd=passwordEncoder.encode("111111");
        logger.info("pwd->"+pwd);
		return "auth/login";
	}
	
//	@Deprecated
//	@RequestMapping(value="/auth",method=RequestMethod.POST)
//	public String auth(HttpServletRequest request,Model model){
//		String userName="test";
//		UserDetails userDetails = customUserDetailsService.loadUserByUsername(userName);
//		Authentication authentication = new UsernamePasswordAuthenticationToken(
//		        userDetails, userDetails.getPassword(), userDetails.getAuthorities());
//		SecurityContext securityContext = SecurityContextHolder.getContext();
//		securityContext.setAuthentication(authentication);
//		HttpSession session = request.getSession(true);
//		       session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
//
//		       return "login";
//	}
//	@RequestMapping("/userlistview")
//	public String listView(HttpServletRequest request,Model model){
//		return "user_list";
//	}
//	@RequestMapping("/userlist")
//	@ResponseBody
//	public SimpleListResult getList(HttpServletRequest request,int page,int rows){
//
//		SimpleListResult slr=new SimpleListResult();
//		slr.setTotal(resultModel.getCount());
//		slr.setRows(srrList);
//
//		return slr;
//	}
	
//	@RequestMapping("/useredit")
//	public String edit(HttpServletRequest request,long uId,Model model){
//
//
//		LOG.info("params->"+request.getParameterNames().toString());
//		LOG.info("uId->"+uId+"-"+uId);
//
//		model.addAttribute("userModel", userModel);
//		AuthorityConstant[] auths=AuthorityConstant.getAll();
//		model.addAttribute("auths", auths);
//
//		return "user_edit";
//	}
	

//	@InitBinder
//	public void initBinder(WebDataBinder binder) {
//	    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//	    dateFormat.setLenient(false);
//	    binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, false));
//	}
    private boolean isInterior(final MUserDetail mUserDetail){
        List<RoleInfo> roleInfoList= mUserDetail.getRoleInfoList();
        if(CollectionUtils.isEmpty(roleInfoList)){
            return false;
        }
        for(RoleInfo roleInfo:roleInfoList){
            if(roleInfo.getRoletype()== RoleType.INTERIOR.getCode()){
                return true;
            }
        }

        return false;
    }
    @RequestMapping(value = "/default")
    public String myDefault(HttpServletRequest request,HttpServletResponse response,String from){
        if(SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof UserModel){
            /*if(!"index".equals(from)) {
                //从cookie中读取上次访问的页面
                Cookie[] cookies = request.getCookies();
                if(cookies!=null&&cookies.length>0)
                for(Cookie c :cookies ){
                    System.out.println(c.getName()+"--->"+c.getValue());
                    if("requestUrl".equals(c.getName())){
                        return "redirect:"+c.getValue();
                    }
                }
            }*/

            UserModel userDetails = (UserModel) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            logger.info("default-userDetails->"+userDetails);
            MUserDetail mUserDetail=userDetails.getmUserDetail();

            if(isInterior(mUserDetail)){

            }

            //登录成功，记录最近登录时间
            MUserInfo mUserInfo=new MUserInfo();
            mUserInfo.setId(mUserDetail.getId());
            mUserInfo.setLastLoginTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
            try {
                muserservice.modifyUserInfo(mUserInfo);
            } catch (Exception ex) {
                logger.error("记录最近登录时间失败",ex);
            }
            //没有邮箱或手机号跳转到用户资料编辑页面
            /*暂时不用
            if(!"profile".equals(from)) {
                if (StringUtils.isEmpty(mUserDetail.getEmail()) || StringUtils.isEmpty(mUserDetail.getMobilePhone())) {
                    return "redirect:/auth/profile?from=default";
                }
            }*/
            if(StringUtils.isEmpty(mUserDetail.getDefaultUrl())){
                //return "/error_no_default";//显示错误提示
                return "redirect:/";
            }else{
                return "redirect:"+mUserDetail.getDefaultUrl();
            }

        }
        return "redirect:/auth/login";
    }
    @RequestMapping(value = "/denied")
    public String denied(HttpServletRequest request){
        return "/auth/denied";
    }


    @RequestMapping(value = "/changePasswd",method = RequestMethod.POST)
    @OperateLog(value = "修改密码",descriptionGenerator = DefaultDescriptionGenerator.class)
    @ResponseBody
    public SimpleResponseBody changePasswd(HttpServletRequest request, Model model, String oldPasswd, String passwd, String repasswd) {
        logger.info("changePasswd->"+oldPasswd+","+passwd+","+repasswd);
        SimpleResponseBody<MUserInfo> srb=new SimpleResponseBody<MUserInfo>();;
        srb.setOk(false);
        if(SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof UserModel){
            UserModel userDetails = (UserModel) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            logger.info("default-userDetails->"+userDetails);
            MUserDetail mUserDetail=userDetails.getmUserDetail();
            if(mUserDetail.getPasswd().equals(passwordEncoder.encode(oldPasswd))){
                if(repasswd.equals(passwd)){
                    MUserSaveInfo mUserSaveInfo=new MUserSaveInfo();
                    mUserSaveInfo.setId(mUserDetail.getId());
                    mUserSaveInfo.setPasswd(passwordEncoder.encode(passwd));
                    try {
                        muserservice.modifyUser(mUserSaveInfo);
                        srb.setOk(true);
                        srb.setMsg("用户修改成功");
                    } catch (Exception ex) {
                        srb.setMsg("发生了未知错误");
                        logger.warn(ex.getMessage(),ex);
                    }
                }else{
                    srb.setMsg("两次输入的密码不一致");
                }
            }else{
                srb.setMsg("输入的旧密码错误！");
            }

        }else {
            srb.setMsg("没有登录，请先登录!");
        }

        return srb;

    }

    //个人资料
    @RequestMapping(value = "/profile")
    public String profile(HttpServletRequest request,Model model,String from){
        if("default".equals(from)){
            model.addAttribute("toDefault",true);
        }else{
            model.addAttribute("toDefault",false);
        }
        if(SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof UserModel){
            UserModel userDetails = (UserModel) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            logger.info("default-userDetails->"+userDetails);
            MUserDetail mUserDetail=userDetails.getmUserDetail();

            //角色
            List<String> rList=new ArrayList<>();
            List<RoleInfo> roleInfoList=mUserDetail.getRoleInfoList();
            logger.debug("roleInfoList->"+roleInfoList);
            for(RoleInfo roleInfo:roleInfoList){
                rList.add(roleInfo.getDescription());
            }

            //权限
            List<AuthInfo> authInfoList=mUserDetail.getAuthInfoList();
            logger.debug("authInfoList->"+authInfoList);

            UserProfile userProfile=new UserProfile();
            DataConverter<MUserDetail,UserProfile> dataConverter=new DataConverter<>(mUserDetail,userProfile);
            dataConverter.convert();
            userProfile.setRoleInfoList(rList);
            userProfile.setStatus(UserStatus.getByCode(mUserDetail.getStatus()).getDescription());

            model.addAttribute("userProfile",userProfile);
            if(StringUtils.isEmpty(mUserDetail.getEmail())||StringUtils.isEmpty(mUserDetail.getMobilePhone())){
                model.addAttribute("alert",true);
            }else{
                model.addAttribute("alert",false);
            }
        }


        return "/auth/profile";
    }

    /**
     * 保存修改的内容
     * */
    @RequestMapping(value = "/profile_save",method = RequestMethod.POST)
    @OperateLog(value = "编辑用户资料",descriptionGenerator = DefaultDescriptionGenerator.class)
    @ResponseBody
    public SimpleResponseBody saveUser(HttpServletRequest request, Model model,String realName,String email,String mobilePhone) {
        SimpleResponseBody<MUserInfo> srb=new SimpleResponseBody<MUserInfo>();
        srb.setOk(false);
        //验证邮箱有效性
        if(!StrCheckUtil.checkEmail(email)){
            srb.setMsg("请输入有效的邮箱地址");
            return srb;
        }
        //验证手机号有效性
        if(!StrCheckUtil.validPhoneNum("2",mobilePhone)){
            srb.setMsg("请输入有效的手机号");
            return srb;
        }

        if(SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof UserModel) {
            UserModel userDetails = (UserModel) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            logger.info("default-userDetails->" + userDetails);
            MUserDetail mUserDetail = userDetails.getmUserDetail();
            if(mUserDetail.getId()<=0){
                srb.setMsg("请先登录！");
                return srb;
            }
            try {
                MUserInfo userInfo = new MUserInfo();
                userInfo.setId(mUserDetail.getId());
                //userInfo.setRealName(realName);
                userInfo.setEmail(email);
                userInfo.setMobilePhone(mobilePhone);
                MUserInfo userInfo1 = muserservice.modifyUserInfo(userInfo);
                mUserDetail.setRealName(userInfo1.getRealName());
                mUserDetail.setEmail(userInfo1.getEmail());
                mUserDetail.setMobilePhone(userInfo1.getMobilePhone());
                srb.setOk(true);
                srb.setMsg("用户资料保存成功");
                srb.setEntity(userInfo1);
            } catch (Exception ex) {
                srb.setMsg("发生了未知错误");
                logger.warn(ex.getMessage(),ex);
            }
        }else{
            srb.setMsg("请先登录！");
        }
        return srb;

    }

}
